package com.xiaostudy.config;

import com.xiaostudy.pojo.User;
import com.xiaostudy.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

//@Component
public class UserRealm extends AuthorizingRealm {
    //实现授权与认证的功能

    @Autowired
     private UserService service;

    @Override
    //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("执行了授权功能");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        String authority = user.getAuthority();
        System.out.println("当前用户："+user.getId()+"的权限为："+authority);
        //添加权限   这个权限是从用户表中查询出来的，后期会根据这个超级权限去操作vip用户和普通用户
        info.addStringPermission(authority);

        return info;
    }

    @Override
    //认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了认证的功能");
        //思路:通过表单传递过来的数据进行封装查找，判断账号密码额正确性。
        UsernamePasswordToken usernamePasswordToken= (UsernamePasswordToken) token;
        //获取username
        String usercount = usernamePasswordToken.getUsername();
        User user = service.getUserByUserCount(usercount);
        if (user==null){
            return null;    //异常抛出unknownAccountException
        }else {
            //用户是存在的
            Subject currentSubject = SecurityUtils.getSubject();
            Session session = currentSubject.getSession();
            session.setAttribute("loginUser",user);

            String password = user.getPassword();
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, password, "");
            return simpleAuthenticationInfo;
        }
    }
}
